/**
 * 宽带预约列表
 */
(function($) {
  var pageData = {};
  var pageCount = 1;
  var filterType = 3;
  var pageNumber = 0;
  var custPageNumber = 0;
  var groupList = new Array();
  var custList = new Array();

  /*
  封装参数
  */
  var getHttpParams = function() {
    var params = "?";
    var myParam = getParams();
    if (myParam) {
      params += myParam;

    }
    return params;
  };

  var isDigital = function(keyword) {
    var reg = /^[0-9]*$/;
    if (reg.test(keyword)) {
      return true;
    }
    return false;
  }

  var invalidParam = function(val, errorMsg) {
    console.log("val=" + val + ",msg=" + errorMsg);
    if (val) {
      return false;
    } else {
      showAlertMessage(errorMsg);
      return true;
    }
  }

  var getOpenBroadbandParamsEx = function() {
    var params = new Object();
    params["bd.bd_id"] = getParamValue("bd_id"); //宽带ID
    params["bd.bd_name"] = decodeURIComponent(getParamValue("BdName")); //宽带名称
    params["bd.user_id"] = getParamValue("userId"); //用户userid
    params["bd.org_id"] = getParamValue("storeId"); //用户所属机构id
    params["bd.build_addr_id"] = getParamValue("build_addr_id"); //小区地址为，小区搜索接口返回的AddressId
    params["bd.add_expand_addr"] = decodeURIComponent(getParamValue("add_expand_addr")); //小区标准地址，此为小区地址搜索接口返回的AddressName
    params["bd.login_no"] = getParamValue("EmpCode"); //工号
    params["bd.group_id"] = getParamValue("group_id"); //地市group_id，如成都为2
    params["bd.region_id"] = getParamValue("CityCodeId"); //地市代码,如成都为11
    params["bd.id_iccid"] = getParamValue("id_iccid"); //身份证号
    params["bd.cust_id"] = getParamValue("cust_id"); //客户id，sChkBlPhone返回CUST_ID
    params["bd.cust_name"] = decodeURIComponent(getParamValue("cust_name")); //客户名称
    params["bd.cust_address"] = decodeURIComponent(getParamValue("cust_address")); //客户地址
    params["bd.id_address"] = decodeURIComponent(getParamValue("id_address")); //证件地址
    params["bd.user_group"] = getParamValue("NumberCode"); //工号对应组织机构代码如高勇洲为67558
    params["bd.prod_id"] = getParamValue("prod_id"); //宽带产品标示，为qryBroadPrc返回的产品标示
    params["bd.prod_prcid"] = getParamValue("prod_prcid"); //宽带资费，为qryBroadPrc返回的宽带资费    
    params["bd.business_code"] = getParamValue("business_code"); //宽带资费，为qryBroadPrc返回的宽带资费    
    params["bd.prepay_fee"] = getParamValue("prepay_fee"); //由s1093GetPrcInfo接口返回的PRE_PAY_FEE
    params["bd.enter_fee"] = getParamValue("enter_fee"); //由s1093GetPrcInfo接口返回的ENTER_FEE
    params["bd.ma_fee"] = getParamValue("ma_fee"); //由s1093GetPrcInfo接口返回的MA_FEE    
    params["bd.con_phone"] = getParamValue("Phone"); //联系人号码
    params["bd.cfm_login"] = $("#broadband_account_no_domains").val(); //宽带账号，与sChkSvcNoSc接口传参一致
    params["bd.user_passwd"] = $("#broadband_password").html(); //宽带密码，至少6位
    params["bd.domains"] = getParamValue("domains"); //由s1093GetPrcInfo接口返回的DOMAINS
    params["bd.enter_num"] = getParamValue("enter_num"); //由s1093GetPrcInfo接口返回的ENTER_NUM
    params["bd.add_inter_mode"] = decodeURIComponent(getParamValue("add_inter_mode")); //接入方式，由小区地址搜索接返回的EnterType
    params["bd.band_width"] = getParamValue("band_width"); //由s1093GetPrcInfo接口返回的BAND_WIDTH   
    params["bd.contract_no_2"] = ""; //第二联系人号码
    params["bd.address_id"] = getParamValue("address_id"); //小区地址id，小区地址搜索接口返回的AreaCode不做处理，若有{}之类的则保留
    params["bd.address"] = decodeURIComponent(getParamValue("address")); //小区地址，小区地址搜索接口返回的AreaAddress
    params["bd.add_coop_mode"] = decodeURIComponent(getParamValue("add_coop_mode")); //网络归属，小区地址搜索接口返回的NetAttr
    params["bd.work_flag"] = getParamValue("work_flag"); //是否需要施工，小区地址搜索接口返回的WorkFlag
    params["bd.region_value"] = decodeURIComponent(getParamValue("region_value")); //小区地址搜索时选择的，区县值
    params["bd.area_name"] = decodeURIComponent(getParamValue("area_name")); //小区名称，小区地址搜索接口返回的AreaName    
    params["bd.id_validdate"] = getParamValue("id_validdate"); //证件有效期，为合账校验接口获取

    add_product_list = ""; //由qryInternetTV查询的  互联网产品编码#互联网资费编码#MAC地址 其中MAC地址为可选。参数示例：APAZ12261#ACAZ25120#或者APAZ12261#ACAZ25120#【MAC地址】
    prod_id2 = "";
    tvType = $("#tv_type").val();
    if (tvType != 'none') {
      add_product_list = tvType.replace('|', '#') + "#" + $('#mac_1').val();
      prod_id2 = tvType.split('|')[0];
      console.log("prod_id2=prod_id2");
    }
    params["bd.add_product_list"] = add_product_list; //add_product_list
    params["bd.prod_id2"] = prod_id2; //电视的产品编码，qryInternetTV接口返回
    params["empPhonbe"] = getParamValue("phonenumber");
    params["bd.sale_type"] = getParamValue("saleType");
    return params;
  }

  var getParameterValue = function(name) {
    return getParamValue(name);
  }

  var showTvTypeList = function(data) {
    console.log("showTvTypeList enter");
    outData = data.OUT_DATA;
    console.log("outData:" + JSON.stringify(outData));
    var $tvList = $('#amz-list');
    var source = $tvList.text();
    var template = Handlebars.compile(source);

    tvList = outData.ROW;
    var data = {
      list: tvList,
      "error": "无费率数据!"
    };
    var html = template(data);
    $tvList.before(html);
  }

  var checkParams = function() {
    tvType = $("#tv_type").val();
    if (tvType != 'none') {
      mac1 = $("#mac_1").val();
      if (invalidParam(mac1, "请填写MAC1地址")) {
        return false;
      }
      // mac2 = $("#mac_2").val();
      // if (invalidParam(mac2, "请填写MAC2地址")) {
      //   return false;
      // }
      // mac3 = $("#mac_3").val();
      // if (invalidParam(mac3, "请填写MAC3地址")) {
      //   return false;
      // }
    }
    phoneNumber = getParamValue("phone");
    if (invalidParam(phoneNumber, "参数异常：当前号码为空！")) {
      return false;
    }
    feeID = $("#tv_type").val();
    if (invalidParam(feeID, "请选择V网资费")) {
      return false;
    }
    return true;
  }

  var submitBroadband = function() {
    if (!checkParams()) {
      return;
    }
    var empCode = getParamValue("empCode");
    callSubmitBroadband(phoneNumber, empCode, feeID);
  }

  var processSChkSvcNoScResult = function(data, account, domains) {
    console.log("data.resCode=" + data.RETURN_CODE);
    closeLoadingModal();
    if (data.RETURN_CODE != 0) {
      console.log('show change-account-modal');
      /*该账号已经存在，需要增加后缀*/
      $("#account_info").html("登录账号&nbsp;" + account + "@" + domains + "&nbsp;已存在，请修改登录帐号");
      var options = {
        closeViaDimmer: false
      };
      $('#change-account-modal').modal(options);
    } else {
      $("#broadband_no").html(account + "@" + domains);
      if (domains.toUpperCase() == 'CMCC') {
        $("#broadband_account_no_domains").val(account);
      } else {
        $("#broadband_account_no_domains").val(account + "@" + domains);
      }
      $("#submit_btn").removeAttr('disabled');
      $("#change_pwd_btn").removeAttr('disabled');
    }
  }

  var closeLoadingModal = function() {
    $('#modal').modal('close');
  }

  var showLoadingModal = function() {
    $('#modal').modal('open');
  }

  var processSuccess = function() {
    $('#modal-submit').modal('close');
    var orgParams = getParamValue("orgParams");
    if (orgParams == null) {
      orgParams = getCookie("orgParams");
    } else {
      orgParams = decodeURIComponent(orgParams);
    }
    console.log("orgParams=" + orgParams);
    type = getParamValue("type");
    //根据type作不同跳转
    if (type == "1") {
      //校园专区
      window.location.replace("index.html?" + orgParams);
    } else if (type == "2") {
      //大市场
      window.location.replace("bd_openacct_list.html?" + orgParams);
    }
  }

  var callSubmitBroadband = function() {
    $('#modal-submit').modal('open');
    params = getOpenBroadbandParamsEx();
    var url = "../../broadbandOpenOrder/commitBdOrder";
    $.ajax({
      type: "post",
      // contentType: "application/json",
      data: params,
      url: url,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(result) {
        console.info(result);
        data = $.parseJSON(result);
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        console.info(data);
        if (data.resultCode == 1000) {
          $("#modal_content").html("宽带开户成功！");
          setTimeout(processSuccess, 2000);
        } else {
          $('#modal-submit').modal('close');
          console.log("message=" + data.message);
          showAlertMessage("宽带开户失败," + data.message);
        }
      },
      error: function(textStatus) {
        $('#modal-submit').modal('close');
        showAlertMessage("宽带开户失败！");
        console.info("request error:" + textStatus);
      }
    });
  };
  //sChkSvcNoSc（登录账号校验接口效验账号是否存在）
  var callSChkSvcNoSc = function(bdAccount, domains) {
    var url = Constants.apiV2HostRest + "sChkSvcNoSc";
    var data = {
      "BODY": {
          "PHONE_NO": getParamValue("phonenumber"),
          "REQUEST_INFO": {
              "OPR_INFO": {
                  "REGION_ID": getParamValue("CityCodeId"),
                  "CHNNEL_TYPE": "",
                  "LOGIN_NO": getParamValue("EmpCode"),
                  "LOGIN_PWD": "",
                  "IP_ADDRESS": "",
                  "GROUP_ID": getParamValue("group_id"),
                  "AUTHEN_CODE": "",
                  "AUTHEN_NAME": "",
                  "CONTACT_ID": "-1",
                  "OP_CODE": "1000"
              },
              "BUSI_INFO_LIST": {
                  "BUSI_INFO": {
                      "ADD_SERVICE_NO": bdAccount,
                      "ADD_NBR_TYPE": "02",
                      "DOMAIN": domains,
                      "TAFLAG": "3A"
                  }
              }
          }
      }
    };
    console.log("esb.callSChkSvcNoSc.url=" + url);
    console.log("esb.callSChkSvcNoSc.data=" + JSON.stringify(data));
    $.ajax({
      type: "post",
      url: url,
      data: JSON.stringify(data),
      contentType: "application/json",
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        console.log("data:" + JSON.stringify(data));
        pageData = data.ROOT;
        console.info(data);
        processSChkSvcNoScResult(data.ROOT, bdAccount, domains);
      },
      error: function(textStatus) {
        closeLoadingModal();
        showAlertMessage("从服务器获取参数失败，请稍后再试");
        console.info("request error:" + textStatus);
      }
    });
  }

  var invalidParam = function(val, errorMsg) {
    console.log("val=" + val + ",msg=" + errorMsg);
    if (val) {
      return false;
    } else {
      showAlertMessage(errorMsg);
      return true;
    }
  }

  var showAlertMessage = function(message) {
    $("#vgroup-alert-content").html(message);
    $("#vgroup-alert").modal('open');
  }

  var closeAlertMessage = function() {
    $("#vgroup-alert").modal('close');
  }

  /*
  加载数据
  */
  var loadTvServiceList = function() {
    var url = Constants.apiV2HostRest + "sDynSvc";
    console.log("url=" + url);
    var data = {"BODY":{
      "PHONE_NO": getParamValue("phonenumber"),
      "SVC_NAME": "d1093B0004",
      "GROUP_ID": getParamValue("group_id"),
      "LOGIN_NO": getParamValue("EmpCode"),
      "TYPE_CODE_OTHER": "12"
    }};

    $.ajax({
      type: "post",
      contentType: "application/json",      
      url: url,
      data: JSON.stringify(data),
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        console.info(JSON.stringify(data));
        if (data.ROOT.RETURN_CODE != 0) {
          closeLoadingModal();
          showAlertMessage(data.USER_MSG);
        } else {
          showTvTypeList(data.ROOT);
          callSChkSvcNoSc(getParamValue("Phone"), getParamValue("Domains"));
        }
      },
      error: function(textStatus) {
        closeLoadingModal();
        showAlertMessage("获取互联网电视基本产品失败！");
        console.info("request error:" + textStatus);
      },
      complete: function() {
        console.log("always");
      }
    });
  };

  var saveNewPassword = function() {
    password1 = $("#password1").val();
    password2 = $("#password2").val();
    if (password1.length < 6 || password2.length < 6) {
      $("#change_pwd_info").html("密码必须大于6位");
      return;
    }
    if (!password1) {
      // alert("密码不能为空，请输入密码");
      $("#change_pwd_info").html("密码不能为空，请输入密码");
      $("#password1")[0].focus();
      return;
    }
    if (!password2) {
      $("#change_pwd_info").html("密码不能为空，请再次输入密码");
      // alert("密码不能为空，请再次输入密码");
      $("#password2")[0].focus();
      return;
    }
    if (password1 != password2) {
      $("#change_pwd_info").html("两次密码不一致，请重新输入");
      // alert("两次密码不一致，请重新输入");
      return;
    }
    $("#change_pwd_info").html("");
    $("#password").val(password1);
    $('#change-pwd-modal').modal('close');
    $('#broadband_password').html(password1);
  }

  var init = function() {
    phone = getParamValue("Phone");
    $("#phone_no").html(phone);
    broadbandNo = phone;
    domains = getParamValue("Domains");
    $("#broadband_no").html(broadbandNo + "@" + domains);
    console.log('domains=' + domains);
    if (domains.toUpperCase() == 'CMCC') {
      $("#broadband_account_no_domains").val(broadbandNo);
    } else {
      $("#broadband_account_no_domains").val(broadbandNo + "@" + domains);
    }
    broadbandName = decodeURIComponent(getParamValue("BdName"));
    $("#broadband_name").html(broadbandName);
    reservationDate = decodeURIComponent(getParamValue("install_time"));
    $("#reservation_date").html(reservationDate);
    if (broadbandNo) {
      if (broadbandNo.length > 6) {
        password = broadbandNo.substring(broadbandNo.length - 6);
      } else {
        password = broadbandNo;
      }
    }
    $("#password").val(password);
    $("#broadband_password").html(password);
    $("#account_phone").html(phone);
    $("#account_domains").html(domains);
  }

  /**
  解析宽带产品标示数据
  */
  var isDataValid = function(data) {
    var hasData = true;
    if (data) {
      var row = data.ROW;
      if (row) {
        var rowArr = new Array();
        if (row instanceof Array) {
          rowArr = row;
        } else if (row instanceof Object) {
          rowArr.push(row);
        }

        for (var i = 0; i < rowArr.length; i++) {
          row = rowArr[0];
          if (row) {
            var rowValue = row.CODE_VALUE;
            var rowValueArr = rowValue.split("|");
            if (rowValueArr && rowValueArr.length == 3) {
              prodId = rowValueArr[0];
              prodPrcid = rowValueArr[1];
              console.log("searchProductMark prodId = " + prodId);
              console.log("searchProductMark prodPrcid = " + prodPrcid);
            }
          } else {
            hasData = false;
          }
        }
      } else {
        hasData = false;
      }
    } else {
      hasData = false;
    }

    return hasData;
  };

  // /**
  // 宽带产品标示数据正确则提交开户信息
  // */
  // var showProductMark = function(data) {
  //   var hasData = isDataValid(data);

  //   if (!hasData) {
  //     $('#modal-submit').modal('close');
  //     showAlertMessage("资费代码有误，不能办理！");
  //   } else {
  //     submitBroadband();
  //   }
  // };

  /**
    宽带产品标示查询
  */
  // var searchProductMark = function() {
  //   //showLoadingModal();
  //   $('#modal-submit').modal('open');
  //   var url = Constants.campusBdRequestHost + "qryBroadPrc?group_id=" + getParamValue("group_id") + "&region_id=" + getParamValue("CityCodeId") + "&login_no=" + getEmpCode() + "&input_code=" + getParamValue("business_code") + "&type_code_other=12";
  //   console.log("searchProductMark url=" + url);
  //   $.ajax({
  //     type: "post",
  //     url: url,
  //     dataType: "json",
  //     success: function(data) {
  //       //closeLoadingModal();
  //       console.info("searchProductMark data：");
  //       console.info(data);
  //       if (data.resCode != "0000000") {
  //         showAlertMessage(data.resMsg);
  //         return;
  //       }

  //       showProductMark(data.outData);
  //     },
  //     error: function(textStatus) {
  //       //closeLoadingModal();
  //       $('#modal-submit').modal('close');
  //       showAlertMessage("网络失败，请稍后重试！");
  //       console.info("request error:" + textStatus);
  //     }
  //   });
  // };


  $(function() {
    $("#change_pwd_btn").on("click", function() {
      console.log('btn change_pwd_btn clicked');
      /*加载模态窗口*/
      var options = {
        closeOnConfirm: false,
        closeViaDimmer: false
      };
      $('#change-pwd-modal').modal(options);
    });

    $("#save_new_pwd_btn").on('click', function() {
      saveNewPassword();
    });
    $("#submit_btn").on('click', function() {
      submitBroadband();
    });
    $("#change_account_btn").on('click', function() {
      $('#change-account-modal').modal('close');
      phone = getParamValue("Phone");
      suffix = $("#account_suffix").val();
      showLoadingModal();
      callSChkSvcNoSc(phone + suffix, getParamValue("Domains"));
    });
    showLoadingModal();
    init();
    loadTvServiceList();
  }); 
})(jQuery);